import GameUiTools from "GameUiTools";
import GameConfig from "GameConfig";
import GameTools from "GameTools";
import GameInit from "GameInit";

cc.Class({
    extends: cc.Component,

    properties: {
        // 开始游戏按钮
        startGameButton: cc.Node, 
        // 规则按钮
        ruleButton: cc.Node,
        // 排行榜按钮
        rankButtion: cc.Node,
        // 试衣间按钮
        chooseButton: cc.Node,
        // 星星
        star: cc.Prefab,
        // 玩家信息
        headImg: cc.Node,
        userName: cc.Label,
        // 更多游戏按钮
        moreGameBtn: cc.Node
    },

    onLoad () {
        // 初始化
        GameInit.gameInit();
        // 历史最高分
        GameConfig.GAME_HIGHEST_SCORE = GameTools.getItemByLocalStorage("GAME_HIGHEST_SCORE", 0);
        // 选择角色
        GameConfig.CHOOSEN_ROLE_NAME = GameConfig.ROLE_NAME_LIST[GameTools.getItemByLocalStorage("CHOOSEN_ROLE_INDEX", 0)];
        // 开始游戏
        GameUiTools.setButtonClickEvents(this, this.startGameButton, "startGameButtonFunc");
        // 规则按钮
        GameUiTools.setButtonClickEvents(this, this.ruleButton, "showRuleFunc");
        // 排行榜按钮
        GameUiTools.setButtonClickEvents(this, this.rankButtion, "showRankFunc");
        // 选择角色按钮
        GameUiTools.setButtonClickEvents(this, this.chooseButton, "chooseFunc");
        // 点击头像用户授权
        GameUiTools.setButtonClickEvents(this, this.headImg, "authoFunc");
        // 更多游戏
        let programs = GameConfig.NAVIGATE_PROGRAMS;
        if (programs && programs.length > 0) {
            GameUiTools.setButtonClickEvents(this, this.moreGameBtn, "moreGameFunc");
        } else {
            this.moreGameBtn.node.active = false;
        }
        // 星星
        this._settleStars();
        this._login();
    },

    start() {
        this.tex = new cc.Texture2D();
        this.authored = false;
    },

    startGameButtonFunc: function() {
        if (this.authored) {
            this._startGame();
        } else {
            this._login(this._startGame());
        }
        
        // 开启背景音乐
        this._playBgAudio();
        GameUiTools.loadingScene("GameScene");
    },

    _startGame: function() {
        // 开始游戏
        GameTools.ajax('/parkour/game/start', {}, function(data){
            if (data.status == 1) {
                GameConfig.CURRENT_GAME_ID = data.data.gameId;
            }
        }, function(data) {
            console.log(data);
        });
    },

    // 点击头像用户授权
    authoFunc: function() {
        this._login();
    },

    _login(cb) {
        if (!this.authored) {
            let _self = this;
            wx.login({
                success (res) {
                  if (res.code) {
                      _self._autho(res.code, cb);
                  } else {
                    console.log('登录失败！' + res.errMsg)
                  }
                }
            })
        }
    },

    // 用户授权
    _autho(code, cb) {
        let _self = this;
        wx.getSetting({
            success: function (res) {
                var authSetting = res.authSetting
                if (authSetting['scope.userInfo'] === true) {
                    // 用户已授权，可以直接调用相关 API
                    _self._userInfo(code, cb);
                } else if (authSetting['scope.userInfo'] === false) {
                    // 用户已拒绝授权，再调用相关 API 或者 wx.authorize 会失败，需要引导用户到设置页面打开授权开关
                    console.log("用户已拒绝授权");
                } else {
                    // 未询问过用户授权，调用相关 API 或者 wx.authorize 会弹窗询问用户
                    wx.authorize({
                        scope: 'scope.userInfo',
                        success: function(res) {
                            _self._userInfo(code, cb);
                        }
                    })
                }
            }
        })
    },

    _userInfo(code, cb) {
        let _self = this;
        wx.getUserInfo({
            openIdList: ['selfOpenId'],
            success: (userRes) => {
                let userData = userRes.userInfo; // 玩家信息
                if (userData) {
                    let data = {
                        code: code,
                        nickName: userData.nickName,
                        headImg: userData.avatarUrl,
                        city: userData.city,
                        country: userData.country,
                        province: userData.province,
                        sex: userData.gender
                    };
                    GameTools.ajax('/parkour/login', data, function(data){
                        if (data.status == 1) {
                            if (userData.nickName) {
                                _self.userName.string = userData.nickName.toString();
                            }
                            if (userData.avatarUrl) {
                                let userIcon = _self.headImg.getComponent(cc.Sprite);
                                cc.loader.load({
                                    url: userData.avatarUrl,
                                    type: 'jpg'
                                }, (err, texture) => {
                                    if (err) console.error(err);
                                    userIcon.spriteFrame = new cc.SpriteFrame(texture);
                                    _self.authored = true;
                                });
                            } 
                            cb && cb();
                        }
                    }, function(data) {
                        console.log(data);
                    });
                }
            },
            fail: (res) => {
            }
        });
    },

    _playBgAudio() {
        // 调用声音引擎播放声音
        // var bgAudioId = cc.audioEngine.playMusic(this.bgAudio, true);
        // cc.audioEngine.setVolume(bgAudioId, 0.2);
    },

    _settleStars() {
        var starPositions = [
            {x: -251, y: 475, scaleRate: 0.375},
            {x: -173, y: 570},
            {x: -126, y: 463, scaleRate: 0.75},
            {x: -191, y: 309, scaleRate: 0.75},
            {x: 285, y: 515},
            {x: 18, y: 304, scaleRate: 0.5},
            {x: 18, y: 577},
        ];
        
        for(var i = 0; i < starPositions.length; i++) {
            var newStar = cc.instantiate(this.star);
            this.node.addChild(newStar);
            newStar.setPosition(cc.v2(starPositions[i].x, starPositions[i].y));
            if (starPositions[i].scaleRate) {
                newStar.scaleX = starPositions[i].scaleRate;
                newStar.scaleY = starPositions[i].scaleRate;
            }
        }
    },

    showRuleFunc: function() {
        GameUiTools.loadingLayer("panel/Rule");
    },

    showRankFunc: function() {
        GameUiTools.loadingLayer("panel/Rank");
    },

    chooseFunc: function() {
        GameUiTools.loadingLayer("panel/Role");
    },
    moreGameFunc: function() {
        let _self = this;
        let programs = GameConfig.NAVIGATE_PROGRAMS;
        // programs = [
        //     {appId:'wx1e13b29ab6873da6',name:'智商冲冲冲'},
        //     {appId:'wx60dc6bacf553bdfc',name:'忍者对对碰'},
        //     {appId:'wx9992ffec4c3f4abb',name:'小忍的探险之旅'}
        // ];
        let item = programs[Math.floor(Math.random()*programs.length)];
            wx.navigateToMiniProgram({
                appId: item.appId,
                success(res) {
                    if (_self.authored) {
                        _self._saveNavigate(item);
                    } else {
                        _self._login(_self._saveNavigate(item));
                    }
                }
            })
    },
    _saveNavigate: function(item) {
        GameTools.ajax('/parkour/game/navigate', {
            appId: item.appId,
            name: item.name
        }, function(data){}, function(data) {});
    },
});
